package dmas.lab;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

import dmas.lab.models.Contact;
import dmas.lab.models.Friend;

public class FileReader {

	public static List<Contact> readContacts() {
		List<String> stringLines = readFile();
		List<Contact> contacts = null;
		List<Friend> friendList = null;
		
		for (int i = 0; i < stringLines.size(); i++) {
			Contact contact = null;
			String[] splitted = stringLines.get(i).split(" ");
			if (i == 0) {
				contacts = new ArrayList<Contact>(value(splitted[0]));
				friendList = new ArrayList<Friend>(value(splitted[0]));
			}
			for (int j = 0; j < splitted.length; j++) {
				if (j == 0) {
					contact = new Contact(i);
				} else {
					Friend friend = new Friend(value(splitted[j]));
					if(!friendList.contains(friend)){
						friend = changeFriendState(friend);
						friendList.add(friend);
					}else{
						friend = friendList.get(friendList.indexOf(friend));
						friend = changeFriendState(friend);
					}
					contact.addFriend(friend);
				}
			}
			contacts.add(contact);
		}
		return contacts;
	}

	private static Friend changeFriendState(Friend friend) {
		Random rand = new Random();
		int value = rand.nextInt(100);
		if (value <= 33) {
			friend.setState("neutral");
		} else if (value <= 66 && value > 33) {
			friend.setState("loved");
		} else if (value > 66) {
			friend.setState("hated");
		}
		return friend;
	}

	private static int value(String string){
		return Integer.valueOf(string);
	}
	
	private static List<String> readFile() {
		List<String> contactsString = new ArrayList<String>();

		File file = new File("D:\\laborki\\dmas\\contact.txt");
		StringBuilder text = new StringBuilder();
		String NL = System.getProperty("line.separator");
		Scanner scanner = null;
		try {
			scanner = new Scanner(new FileInputStream(file));
			while (scanner.hasNextLine()) {
				String current = scanner.nextLine();
				text.append(current + NL);
				contactsString.add(current);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		scanner.close();
		return contactsString;
	}
}
